﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using SharpBolt.Graphics.GraphicSources;
using SharpBolt.Graphics;

namespace SharpBolt.Serialization
{
    public class GraphicSourceTypesJsonConverter : JsonConverter
    {

        public override bool CanWrite
        {
            get
            {
                return true;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            IGraphicSource graphicSource = value as IGraphicSource;
            writer.WriteValue(graphicSource.Name);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            if (objectType == typeof(ImageSource))
            {
                return ImageSource.LoadImage(reader.Value.ToString());
            }

            if (objectType == typeof(SpriteSource))
            {
                return SpriteSource.LoadSprite(reader.Value.ToString());
            }

            if (objectType == typeof(RasterFontSourse))
            {
                return RasterFontSourse.LoadSharpBoltFont(reader.Value.ToString());
            }

            throw new ApplicationException(String.Format("The given objectType {0} is not supported!", objectType));
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(ImageSource) ||
                    objectType == typeof(SpriteSource) ||
                     objectType == typeof(RasterFontSourse);
        }

    }
}
